<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI助手对话</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .message-fade-in {
            animation: fadeIn 0.3s ease-in-out;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .typing-indicator {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: #9ca3af;
            margin: 0 2px;
            animation: typing 1.4s infinite ease-in-out;
        }
        
        .typing-indicator:nth-child(1) { animation-delay: -0.32s; }
        .typing-indicator:nth-child(2) { animation-delay: -0.16s; }
        
        @keyframes typing {
            0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; }
            40% { transform: scale(1); opacity: 1; }
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen flex flex-col">
    <div class="container mx-auto max-w-4xl flex-1 p-4 flex flex-col">
        <!-- 标题区域 -->
        <header class="text-center py-6">
            <h1 class="text-3xl font-bold text-indigo-600">AI智能助手</h1>
            <p class="text-gray-600 mt-2">与AI助手进行对话，获取帮助与解答</p>
        </header>

        <!-- 对话区域 -->
        <div id="chatContainer" class="flex-1 bg-white rounded-lg shadow-md p-4 mb-4 overflow-y-auto max-h-[60vh]">
            <div class="text-center text-gray-500 py-8" id="emptyState">
                <i class="fas fa-robot text-4xl mb-4 text-indigo-400"></i>
                <p>您好！我是您的AI助手，请问有什么可以帮助您的？</p>
            </div>
            <!-- 对话消息将在这里动态添加 -->
        </div>

        <!-- 输入区域 -->
        <div class="bg-white rounded-lg shadow-md p-4">
            <div class="flex space-x-2">
                <input 
                    type="text" 
                    id="messageInput" 
                    placeholder="输入您的问题..." 
                    class="flex-1 border border-gray-300 rounded-lg px-4 py-3 focus:outline-none focus:ring-2 focus:ring-indigo-500"
                    maxlength="500"
                >
                <button 
                    id="sendButton" 
                    class="bg-indigo-600 text-white px-6 py-3 rounded-lg hover:bg-indigo-700 transition-colors duration-200 flex items-center"
                >
                    <span>发送</span>
                    <i class="fas fa-paper-plane ml-2"></i>
                </button>
            </div>
            <div class="flex justify-between items-center mt-2">
                <span id="charCount" class="text-xs text-gray-500">0/500</span>
                <div id="statusIndicator" class="text-xs text-gray-500 hidden">
                    <i class="fas fa-circle text-green-500 mr-1"></i>
                    <span>AI正在思考中...</span>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 获取DOM元素
        const chatContainer = document.getElementById('chatContainer');
        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');
        const emptyState = document.getElementById('emptyState');
        const charCount = document.getElementById('charCount');
        const statusIndicator = document.getElementById('statusIndicator');

        // 字符计数更新
        messageInput.addEventListener('input', () => {
            charCount.textContent = `${messageInput.value.length}/500`;
        });

        // 发送消息函数
        function sendMessage() {
            const message = messageInput.value.trim();
            if (!message) return;

            // 清空输入框
            messageInput.value = '';
            charCount.textContent = '0/500';

            // 隐藏空状态
            if (emptyState) {
                emptyState.style.display = 'none';
            }

            // 添加用户消息
            addMessage(message, 'user');

            // 显示AI正在思考状态
            statusIndicator.classList.remove('hidden');
            
            // 添加AI消息容器
            const aiMessageElement = addMessage('', 'assistant', true);
            
            // 调用API
            callChatAPI(message, aiMessageElement);
        }

        // 添加消息到对话区域
        function addMessage(content, sender, isTyping = false) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `flex ${sender === 'user' ? 'justify-end' : 'justify-start'} mb-4 message-fade-in`;
            
            const bubbleDiv = document.createElement('div');
            bubbleDiv.className = `max-w-[80%] p-3 rounded-lg ${
                sender === 'user' 
                    ? 'bg-indigo-500 text-white rounded-br-none' 
                    : 'bg-gray-200 text-gray-800 rounded-bl-none'
            }`;
            
            if (isTyping) {
                bubbleDiv.id = 'typingMessage';
                const typingDiv = document.createElement('div');
                typingDiv.className = 'flex space-x-1 items-center';
                typingDiv.innerHTML = `
                    <span class="typing-indicator"></span>
                    <span class="typing-indicator"></span>
                    <span class="typing-indicator"></span>
                `;
                bubbleDiv.appendChild(typingDiv);
            } else {
                bubbleDiv.textContent = content;
            }
            
            messageDiv.appendChild(bubbleDiv);
            chatContainer.appendChild(messageDiv);
            
            // 滚动到底部
            chatContainer.scrollTop = chatContainer.scrollHeight;
            
            return bubbleDiv;
        }

        // 调用聊天API
        function callChatAPI(message, messageElement) {
            // 构建API URL
            const apiUrl = `http://localhost:8080/api/ollama/chat_stream?message=${encodeURIComponent(message)}`;
            
            // 创建EventSource
            const eventSource = new EventSource(apiUrl);
            let responseText = '';
            
            eventSource.onmessage = function(event) {
                try {
                    const data = JSON.parse(event.data);
                    
                    // 检查是否有文本内容
                    if (data.result && data.result.output && data.result.output.text) {
                        responseText += data.result.output.text;
                        
                        // 更新消息显示
                        messageElement.innerHTML = responseText;
                        
                        // 滚动到底部
                        chatContainer.scrollTop = chatContainer.scrollHeight;
                    }
                    
                    // 检查是否结束
                    if (data.result && data.result.metadata && data.result.metadata.finishReason === 'stop') {
                        eventSource.close();
                        statusIndicator.classList.add('hidden');
                    }
                } catch (error) {
                    console.error('解析响应数据出错:', error);
                }
            };
            
            eventSource.onerror = function(event) {
                console.error('EventSource错误:', event);
                eventSource.close();
                statusIndicator.classList.add('hidden');
                
                // 显示错误消息
                messageElement.innerHTML = '<span class="text-red-500">抱歉，发生了错误，请稍后再试。</span>';
            };
            
            // 添加取消按钮
            const cancelButton = document.createElement('button');
            cancelButton.className = 'mt-2 text-xs text-red-500 hover:text-red-700';
            cancelButton.innerHTML = '<i class="fas fa-times mr-1"></i>取消';
            cancelButton.onclick = function() {
                eventSource.close();
                statusIndicator.classList.add('hidden');
                messageElement.innerHTML += '<br><span class="text-gray-500 text-xs">[已取消]</span>';
                cancelButton.remove();
            };
            
            messageElement.appendChild(cancelButton);
        }

        // 绑定发送按钮点击事件
        sendButton.addEventListener('click', sendMessage);

        // 绑定回车键发送
        messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
    </script>
</body>
</html>